import router from '@/router'

export function checkButtonPermission(value) {
  const roles = router?.currentRoute?.meta?.permissions || []
  let hasPermission = false
  if(value && typeof value === 'string'){
    hasPermission = roles.indexOf(value) > -1
  } else if (value && value instanceof Array) {
    if (value.length > 0) {
      const permissionRoles = value

      hasPermission = roles.some(role => {
        return permissionRoles.includes(role)
      })
    }
  } else {
    throw new Error(`need permissions! Like v-permission="admin" or v-permission="['admin','editor']"`)
  }
  return hasPermission
}

function checkPermission(el, binding) {
  const { value } = binding
  let hasPermission = checkButtonPermission(value)

  if (!hasPermission) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
